<?php
/**
 * desc: 框架基类：控制器类分发，配置文件装载
 */
namespace myphp;
use myphp\Configs;
use app\controller;

class Application
{
    // 实例
    private static $instance;
    public $baseDir;
    public $config;

    private function __construct($dirname) {
        $this->baseDir = $dirname;
        $this->config = new Configs();
    }

    // 获取实例
    public static function getInstance($base_dir="") {
        if(!self::$instance) {
            self::$instance = new self($base_dir);
        }
        return self::$instance;
    }

    // 派发控制器类
    public function dispatch() {
        $requestUri = trim($_SERVER['REQUEST_URI'],"/");
        $projectDir = explode("\\",$this->baseDir);
        $currUri = explode("/",$requestUri);
        $routerUri = array_diff($currUri,array_intersect($projectDir,$currUri));
        if(in_array("index.php",$routerUri)) {
            array_diff($routerUri,["index.php"]);
        }
        // 取出了控制器和操作方法
        list($c,$a) = array_values($routerUri);
        $controller = strtolower($c);
        $action = strtolower($a);

        // 可以实例化控制器类派发
        $controllerName = '\\app\controller\\'.$controller;
        $controllerObj = new $controllerName($controller,$action);

        // 调用控制器类的操作方法
//        var_dump($controllerObj->$action());
//        die;

        $controllerConfig = $this->config['controller'];
        $decoratorObjs = [];
        if(isset($controllerConfig[$controller])) {
            $currDecorator = $controllerConfig[$controller]['decorator'];
            foreach ($currDecorator as $key => $value) {
                $decoratorObjs[] = new $value();
            }
        }

        // 给当前控制器的装饰器都执行前置方法
        foreach ($decoratorObjs as $key => $value) {
            $value->beforeAction($controllerObj);
        }

        // 执行控制器方法
        $ret = $controllerObj->$action();

//        var_dump();
//        die;

        // 给当前控制器的装饰器执行后置方法
//        var_dump($currDecorator);
//        die;
    }

}